﻿using Rsd.Dudu;
using Rsd.Dudu.BizModel;
using Rsd.Dudu.Core;
using Rsd.Dudu.DBServices;
using Rsd.Dudu.Helpers;
using Rsd.Faith.Core;
using Rsd.Faith.Models;
using Rsd.Faith.Sys.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace Rsd.Faith.Web.Services
{
    /// <summary>
    /// 定时任务
    /// </summary>
    public class ApiTimerService : BaseService, IApiTimerService
    {
        public override ServiceProxcy Proxcy =>  ServiceProxcy.Sington;

        static bool _isBusying = false;
        /// <summary>
        /// 
        /// </summary>
        public void DoRequestApi(string loginUrl)
        {
            if (_isBusying)
            {
                return;
            }

            Task _task = null;


            if (_task == null)
            {
                _task = new Task(() => {

                    var list = MyType.GetObjects<ApiTimerModel, long>(obj => obj.Enabled == true && obj.Success == 0, obj => obj.SortIndex, SortType.ASC, 100, 0);
                    _isBusying = true;

                    while (list.Length > 0)
                    { 
                        var resp = this.HttpGet(loginUrl);
                        var token = JsonHelper.FormatJsonString(resp.Data).Get<JsonObject>("data").Get<string>("token");
                        foreach (var api in list)
                        {
                            if (api.Method.ToUpper() == "GET")
                            {

                                try
                                {
                                    var rs = this.HttpGet(api.Url+"&___key="+ token, 3000);
                                    api.Respone = rs.Data;
                                    api.Success = JsonHelper.FormatJsonString(rs.Data).Get<bool>("success") ? 1 : -1;
                                }
                                catch (System.Exception ex)
                                {
                                    api.Respone = ex.Message;
                                    api.Success = -1;
                                }
                                 
                            }
                            else
                            {
                                api.Respone = "不支持GET以外的请求"; 
                                api.Success = -1; 
                            }

                            api.SetState(Dudu.BizModel.ObjectStateType.Update);
                            MyType.SaveObjects(api);
                        }

                        list = MyType.GetObjects<ApiTimerModel, long>(obj => obj.Enabled == true && obj.Success == 0, obj => obj.SortIndex, SortType.ASC, 100, 0);
                    }

                    _isBusying = false;
                });

            }

            _task.Start();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="host"></param>
        /// <param name="list"></param>
        public void StartTimer(string host , ApiTimerModel[] list)
        {
            var _host = host;
            var index = DateTime.Now.ToLongTimeStamp();

            foreach (var api in list)
            {
                if (api.Enabled)
                {
                    continue;
                }
                index++;
                if (api.Method.ToUpper() == "GET")
                {

                    api.Url = _host + api.Path;
                    api.Success = 0;
                    api.Enabled = true;
                    api.Respone = "";
                    api.SortIndex = index;
                    api.SetState(Dudu.BizModel.ObjectStateType.Update);
                    MyType.SaveObjects(api);
                }
                else
                {
                    api.Respone = "不支持GET以外的请求";
                    api.Enabled = true;
                    api.Success = -1;
                    api.SetState(Dudu.BizModel.ObjectStateType.Update);
                    MyType.SaveObjects(api);
                }
            }

           
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="host"></param>
        /// <param name="group"></param>
        public void StartTimer(string host, string group)
        {
            var list = this.GetApiList(group, false);
            this.StartTimer(host,list);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="group"></param>
        /// <param name="path"></param>
        /// <param name="text"></param>
        public void NewTimer(string group, string path, string text )
        {
            var timer = new ApiTimerModel(ObjectStateType.New) { Group = group, Path = path, Text = text, Method = "GET", Enabled = false };
            MyType.SaveObjects(timer); 
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="group"></param>
        /// <param name="enable"></param>
        /// <returns></returns>
        public ApiTimerModel[] GetApiList(string group, bool enable)
        {
            return MyType.GetObjects<ApiTimerModel>(obj=>obj.Group == group && obj.Enabled == enable);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override dynamic GetMonitorInfo()
        {
            throw new NotImplementedException();
        }
    }
}
